<!--  -->
<template>
  <div class="add-goods">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图：添加主体 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="商品添加" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0" :pace="200" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 竖直tan栏 -->
      <el-form
        :model="addGoods.addGoodsForm"
        :rules="addGoods.addGoodsFormRules"
        ref="addGoodsRef"
        label-width="70px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          :stretch="true"
          v-model="activeIndex"
          :before-leave="beforeLeaveTab"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoods.addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)" prop="goods_price">
              <el-input v-model="addGoods.addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量(个)" prop="goods_number">
              <el-input v-model="addGoods.addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(g)" prop="goods_weight">
              <el-input v-model="addGoods.addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="cate.cateIds"
                :clearable="true"
                :options="cate.cateList"
                :props="cate.casProps"
                @change="handleCasChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in cate.manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_valsChecked">
                <el-checkbox
                  :label="val"
                  v-for="(val, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in cate.onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              :action="uploadPic.url"
              :headers="uploadPic.header"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">上传图片</el-button>
              <div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoods.addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoodsConfirm('addGoodsRef')" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览窗口 -->
    <el-dialog title="图片预览" :visible.sync="uploadPic.previewVisible" width="50%">
      <img :src="uploadPic.previewPath" alt class="preview-pic" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '0',

      // 添加商品对象
      addGoods: {
        // 添加商品表单数据
        addGoodsForm: {
          goods_name: '',
          goods_cat: '',
          goods_price: 0,
          goods_number: 0,
          goods_weight: 0,
          goods_introduce: '',
          pics: [],
          attrs: []
        },
        addGoodsFormRules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' }
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ],
          goods_cat: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ]
        }
      },
      // 分类对象
      cate: {
        cateList: [],
        casProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          expandTrigger: 'hover'
        },
        cateIds: [],
        manyData: [], // 动态参数列表数据
        onlyData: [] // 静态属性列表数据
      },
      // 图片上传对象
      uploadPic: {
        fileList: [],
        url: 'http://127.0.0.1:8888/api/private/v1/upload', // 上传图片后台地址
        header: {
          Authorization: sessionStorage.getItem('token')
        },
        previewPath: '', // 预览图片地址
        previewVisible: false // 控制预览图片窗口显示
      }
    }
  },

  created() {
    this.getCateList()
  },
  computed: {
    // 分类ID
    cateId() {
      if (this.cate.cateIds.length === 3) {
        return this.cate.cateIds[2]
      }
      return null
    }
  },

  methods: {
    // 获取分类列表
    getCateList() {
      this.axios.get('categories').then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取商品分类列表失败')
        }
        this.cate.cateList = resp.data
        this.$message.success({ message: '获取角色列表成功', duration: 500 })
      })
    },

    // 处理商品分类选择改变
    handleCasChange() {
      this.addGoods.addGoodsForm.goods_cat = this.cate.cateIds.join(',')
      let pm1 = () => {
        return new Promise(resolve => {
          this.getParams()
          resolve()
        })
      }
      let pm2 = () => {
        return new Promise(resolve => {
          this.getAttrs()
          resolve()
        })
      }
      Promise.all([pm1(), pm2()]).then(() => {
        this.addGoods.addGoodsForm.attrs = this.cate.manyData.concat(
          this.cate.onlyData
        )
      })
    },
    // 离开第一项tab也前校验->分类项选择：已选，tab切换；未选，不执行切换
    beforeLeaveTab(activeName, oldActiveName) {
      if (
        oldActiveName === '0' &&
        this.addGoods.addGoodsForm.goods_cat === ''
      ) {
        this.$message.error('商品分类未选择')
        return false
      }
    },
    // tabs切换
    tabClicked() {},
    // 获取动态参数参数
    getParams() {
      this.axios
        .get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('获取商品动态参数失败')
          }
          resp.data.forEach(item => {
            item.attr_vals =
              item.attr_vals === '' ? [] : item.attr_vals.split(',')
            item.attr_valsChecked = [...item.attr_vals]
          })

          this.cate.manyData = resp.data

          this.$message.success({
            message: '获取动态参数成功',
            duration: 500
          })
        })
    },
    // 获取静态属性
    getAttrs() {
      this.axios
        .get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('获取商品静态属性失败')
          }

          this.cate.onlyData = resp.data

          this.$message.success({
            message: '获取静态属性成功',
            duration: 500
          })
        })
    },
    // 处理文件预览
    handlePreview(pic) {
      // 获取预览图片地址
      this.uploadPic.previewPath = pic.response.data.url
      // 显示图片预览窗口
      this.uploadPic.previewVisible = true
    },
    // 处理文件移除
    handleRemove(pic) {
      // 获取移除图片临时路径
      const tmpPath = pic.response.data.tmp_path
      // 查找图片在提交表单图片数组pics中位置
      const index = this.addGoods.addGoodsForm.pics.findIndex(item => {
        return item.pic === tmpPath
      })
      // 调用splice函数删除该图片对象
      this.addGoods.addGoodsForm.pics.splice(index, 1)
    },
    // 处理成功上传图片
    handleSuccess(rep) {
      // 获取返回临时路径
      const tempPath = rep.data.tmp_path
      // 存入提交表单对象中
      this.addGoods.addGoodsForm.pics.push({ pic: tempPath })
    },
    // 添加商品确认
    addGoodsConfirm(form) {
      // 校验表单
      this.$refs[form].validate(valid => {
        // 校验失败
        if (!valid) {
          return this.$message.error('添加商品表单项格式不正确，请重新添加')
        }
        // 校验成功
        // 发送添加请求
        this.axios.post('goods', this.addGoods.addGoodsForm).then(resp => {
          if (resp.meta.status !== 201) {
            return this.$message.error('商品添加失败')
          }
          // 商品添加成功，跳转商品页面
          this.$router.push('/goods')
        })
      })
    }
  },

  components: {}
}
</script>

<style lang='scss' scoped>
.add-goods {
  .el-checkbox-group {
    // 复选框组复选框
    .el-checkbox {
      margin: 0;
    }
  }
  // 预览图片
  .preview-pic {
    width: 100%;
  }
  // 添加按钮
  .addBtn {
    margin-top: 15px;
  }
}
</style>
